<template>
  <div class="container-box">
    <div class="table-wrap">
      <div class="filter-box">
        <el-form :inline="true" :model="query" class="demo-form-inline">
          <template v-for="(column, index) in columns.filter(d => d.isFilter)">
            <el-form-item :key="index" :label="column.title">
              <el-select v-if="column.type === 'dict'" v-model="query[column.key]" filterable multiple :clearable="column.clearable" @change="getData">
                <el-option v-for="item in handleDict(column.dictName).data" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-date-picker v-else-if="column.key === 'create_time'" v-model="query[column.key]" :clearable="column.clearable" type="daterange" :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"  @change="getData"/>
              <el-input v-else v-model="query[column.key]" :placeholder="`请输入${column.title}`" :clearable="column.clearable" @change="getData" />
            </el-form-item>
          </template>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="getData"></el-button>
          </el-form-item>
        </el-form>
        <el-row class="button-row">
          <el-button type="primary" @click="handleTableOp('addOrder1')">采购入库</el-button>
          <el-button type="primary" @click="handleTableOp('addOrder2')">销售出库</el-button>
          <el-button type="primary" icon="el-icon-setting" @click="handleColumnForm"></el-button>
        </el-row>
      </div>
      <div class="table-box">
        <el-table :data="list" border stripe header-row-class-name="table-header-row" show-summary :summary-method="getSummaries">
          <template v-for="(column, index) in columns.filter(d => d.isTable)">
            <el-table-column :key="index" :prop="column.key" :label="column.title" :width="column.width">
              <template slot-scope="scope">
                <div v-if="column.key === ''" class="">{{ scope.row[column.key] }}</div>
                <el-select v-else-if="column.key === 'status'" v-model="scope.row[column.key]" @change="changeStatus(scope.row, $event)">
                  <el-option v-for="item in handleDict(column.dictName).data" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <div v-else class="">{{ handleRowResult(column, scope.row) }}</div>
              </template>
            </el-table-column>
          </template>
          <el-table-column label="操作" width="100px">
            <template slot-scope="scope">
              <el-row class="button-row">
                <el-button size="mini" type="primary" icon="el-icon-document" circle @click="handleTableOp('fetch', scope.row)" />
                <el-button size="mini" type="primary" icon="el-icon-edit-outline" circle @click="handleTableOp('edit', scope.row)" />
              </el-row>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination :current-page="paging.page" :page-sizes="pageSizes" :page-size="paging.limit" layout="total, sizes, prev, pager, next, jumper" :total="paging.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
      <v-column-form ref="columnFormRef" @callback="handleColumnFormComCb" />
    </div>
  </div>
</template>

<script>
import { storeIndex, storeHouse, storeAdd, addStoreHouse } from '../../api/store';
import { orderIndex, updataStatus } from '@/api/order';
import curde from '@/mixins/curde';
import ColumnForm from '@/components/ColumnForm'

export default {
  name: 'Order',
  mixins: [curde],
  components: {
    vColumnForm: ColumnForm
  },
  data() {
    return {
      storeId: '',
      // 类型：1: 采购入库, 2: 销售出库, 3: 同价调拨,  4: 其他入库, 5: 采购退货, 6: 报溢单, 7: 报损单, 8: 其他出库
      columns: [
        { title: '订单号', key: 'order_no', type: 'text', isFilter: true, clearable: true, isTable: true, isForm: false },
        { title: '客户名称', key: 'company_name', type: 'text', isFilter: true, clearable: true, isTable: true, isForm: true },
        { title: '数量1', key: 'total_num', type: 'text', isFilter: false, isTable: true, isForm: true },
        { title: '数量2', key: 'total_num2', type: 'text', isFilter: false, isTable: true, isForm: true },
        { title: '类型', key: 'order_type', type: 'dict', dictName: 'order_type', isFilter: true, clearable: true, isTable: false, isForm: false, width: '100px' },
        { title: '状态', key: 'status', type: 'dict', dictName: 'order_status', isFilter: true, clearable: true, isTable: true, isForm: true, width: '100px' },
        { title: '订单金额', key: 'total_price', type: 'number', isFilter: false, isTable: true, isForm: false },
        { title: '创建时间', key: 'create_time', type: 'date', format: 'YYYY-MM-DD', isFilter: true, clearable: true, isTable: true, isForm: true  },
        { title: '备注', key: 'remarks', type: 'text', isFilter: false, isTable: true, isForm: true }
      ],
      list: [],
      query: {
        order_no: '',
        company_name: '',
        status: [],
        create_time: [],
        startTime: '',
        endTime: ''
      },
      dict: {},
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '本月',
          onClick(picker) {
            const date = new Date();
            const year = date.getFullYear();
            const month = date.getMonth() + 1;
            // 设置日期为32。计算当前月份有多少天。
            date.setDate(32);
            const day = 32 - date.getDate();
            
            const start = new Date(`${year}-${month}-01`);
            const end = new Date(`${year}-${month}-${day}`);

            start.setTime(start.getTime());
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    };
  },
  computed: {
    orderStatus() {
      const data = this?.dictDetails?.order_status?.data || [];
      return data;
    },
    orderDict() {
      if (this.orderStatus.length === 0) {
        return {};
      }
      const orderDict = {};
      this.orderStatus.forEach(d => {
        orderDict[d.value] = d.label;
      });
      return orderDict;
    }
  },
  watch: {
    storeHouseDialogVisible(val, oldVal) {
      this.storeHouseForm = {}
    },
    'query.create_time': {
      handler(val) {
        if (val && val.length) {
          console.log('val==', val);
          this.query.startTime = this.$moment(new Date(val[0])).format('YYYY-MM-DD 00:00:00');
          this.query.endTime = this.$moment(new Date(val[1])).format('YYYY-MM-DD 23:59:59');
        }
        else {
          this.query.startTime = '';
          this.query.endTime = '';
        }
        this.$set(this, 'query', this.query)
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    console.log('handleDict(column.dictName).data==', this.handleDict('order_status'));
    this.getData();
    console.log('order/index--order_status==', this.order_status);
  },
  methods: {
    handleColumnForm() {
      const columns = this.$json.cloneDeep(this.columns);
      this.$refs.columnFormRef.showDialog(columns);
    },
    handleColumnFormComCb(columns) {
      console.log('handleColumnFormComCb==', columns);
      // this.columns = this.$json.cloneDeep(columns);
      this.$set(this, 'columns', columns);
      this.$refs.columnFormRef.closeDialog();
    },
    // 更新订单状态
    async changeStatus(row, value) {
      console.log('row, value==', row, value);
      if (this.saving) {
        return;
      }
      try {
        const res = await updataStatus({ id: row.id, status: value });
        console.log('updataStatus--res==', res);
        this.$message.success('操作成功');
        this.saving = false;
      } catch (e) {
        this.$message.error('操作失败');
        this.saving = false;
      }
    },
    // 获取数据
    async getData() {
      const payload = this.createPayload(this.query)
      payload.paging = this.paging;
      if (payload.status) {
        payload.status = payload.status.join(',');
      }
      console.log('payload==', payload);
      let list = [];
      let count = 0;
      try {
        const res = await orderIndex(payload);
        console.log('orderIndex--res==', res);
        list = res.data.list || [];
        count = res.data.count || 0;
      } catch (e) {
        console.log('e==', e);
      }
      this.paging.total = count;
      this.list = list || [];
      this.$set(this.paging, 'total', count);
      return;
    },
    // 操作按钮
    handleTableOp(type, row) {
      if (['addOrder1', 'addOrder2'].includes(type)) {
        let oType;
        if (type === 'addOrder1') {
          oType = '1';
        }
        if (type === 'addOrder2') {
          oType = '2';
        }
        this.$router.push({ path: `/order/add/0/${new Date().getTime()}`, query: { oType } });
      }
      else if (type === 'fetch') {
        this.$router.push({ path: `/order/${type}/${row.id}/${new Date().getTime()}` });
      }
      else if (type === 'edit') {
        this.$router.push({ path: `/order/${type}/${row.id}/${new Date().getTime()}` });
      }
    },
    // table 渲染
    handleRowResult(item, row) {
      // console.log('handleRowResult--item', item, row);
      const value = row[item.key];
      if (item.key === 'status') {
        return this?.orderDict && this.orderDict[value] ? this.orderDict[value] : value;
      }
      if (item.key === 'stock') {
        if (row.stock && row.unit_name2 && row.unit_convert !== row.unit_convert2) {
          const unitNum = row.stock % row.unit_convert2;
          const unitNum2 = Math.floor(row.stock / row.unit_convert2);
          return `${unitNum2}${row.unit_name2}${unitNum}${row.unit_name}`
        }
        return `${row.stock}${row.unit_name}`
      }
      if (item.key === 'store_id') {
        return this.dict.store[value]?.store_name || value;
      }
      if (item.type === 'date') {
        return item.format ? this.$moment(value).format(item.format) : value;
      }
      return value || '';
    },
    // table 合计；
    getSummaries(params) {
      console.log('getSummaries--params', params);
      const { columns, data } = params;
      console.log('getSummaries==', columns, data);

      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总价';
          return;
        }
        if (['goods_num', 'goods_num2', 'total_price'].includes(column.property)) {
          const values = data.map(item => Number(item[column.property]));
          console.log('getSummaries--values==', values);
          if (!values.every(value => isNaN(value))) {
            let unitName = '';
            sums[index] = values.reduce((prev, curr, cIndex) => {
              // console.log('data[curr]==', prev, curr, data[cIndex]);
              if (column.property === 'goods_num') {
                unitName = data[cIndex].unit_name;
              }
              else if (column.property === 'goods_num2') {
                unitName = data[cIndex].unit_name2;
              }
              else if (column.property === 'total_price') {
                // unitName = '元'
              }

              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] += unitName;
          } else {
            sums[index] = 'N/A';
          }
        }
        else {
          sums[index] = '-';
        }
      });
      return sums
    }
  }
}

</script>
<style lang="scss" scoped>
.container-box {
  padding: 20px;
  .table-wrap {
    margin-top: 40px;
    .filter-box {
      margin-bottom: 10px;
    }
    ::v-deep .table-header-row {
      color: #000;
      font-weight: bold !important;
    }
  }
}
.pagination {
  margin-top: 10px;
}
</style>
